package com.xkw.demo.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 *  springboot默认的异常处理是/error接口。可以通过实现ErrorController来重新定义对错误信息的处理。
 * @author admin
 *
 */
@Controller
public class BasicErrorController implements ErrorController {
	
	/**
	 * 处理错误请求，返回错误页面error.html
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/error", produces="text/html")
	public Object handleErrorHtml(ModelMap map, HttpServletRequest request) {
		map.put("statusCode", request.getAttribute("javax.servlet.error.status_code"));
		map.put("url", request.getAttribute("javax.servlet.error.request_uri"));
		map.put("ex", request.getAttribute("javax.servlet.error.exception"));
		return getErrorPath();
	}
	
	/**
	 * 处理错误请求，返回错误json
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/error")
	public Object handleErrorHtml(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("statusCode", request.getAttribute("javax.servlet.error.status_code"));
		map.put("url", request.getAttribute("javax.servlet.error.request_uri"));
		map.put("ex", request.getAttribute("javax.servlet.error.exception"));
		return map;
	}
	

	@Override
	public String getErrorPath() {
		return "/error";
	}

}
